#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>

#define BUFFER_SIZE 256

void error(char *msg)
{
	perror(msg);
	exit(1);
}
int main(int argc, char *argv[])
{
	int sockfd, portno, n;
	socklen_t cli_length;
	char buffer[BUFFER_SIZE];
	struct sockaddr_in serv_addr, cli_addr;

	if(argc < 2) {
		fprintf(stderr,"ERROR: port no not provided\n");
		exit(1);
	}

	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if(sockfd < 0)
		error("ERROR: Failed to create server socket\n");

	portno = atoi(argv[1]);

	bzero((char *) &serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = portno;
	serv_addr.sin_addr.s_addr = INADDR_ANY;

	if((bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr))) < 0 )
		error("ERROR: Failed to bind server socket\n");

	cli_length = sizeof(struct sockaddr_in);

	while(1) {
		bzero(buffer, BUFFER_SIZE);

		n = recvfrom(sockfd, buffer, BUFFER_SIZE, 0, (struct sockaddr *) &cli_addr, &cli_length);
		if(n < 0)
			error("ERROR: Failed to receive message from client");

		printf("Client's message %s : %s", inet_ntoa(cli_addr.sin_addr), buffer);

		n = sendto(sockfd, "Got your message\n", 17, 0, (struct sockaddr *) &cli_addr, cli_length);
		if(n < 0)
			error("ERROR: Failed to send message to client");
	}

	return 0;
}
